package com.cqu.ssologin.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import com.cqu.ssologin.pojo.User;
import com.cqu.ssologin.utils.LoginCacheUtil;

@Controller
@RequestMapping("/view")
public class ViewController {
    
    @GetMapping("/login")
    public String login(@RequestParam(required = false, defaultValue = "") String target,
                        HttpSession session, 
                        @CookieValue(required = false, value ="TOKEN") Cookie cookie){
        //没有target参数就赋为空，然后判断，为空就默认跳到首页main
        if(StringUtils.isEmpty(target)){
            target = "http://localhost:9010/view/index";
        } 
        //若已登录的用户再次访问登录系统，就要重定向
        if(cookie != null){
            String value = cookie.getValue();
            User user = LoginCacheUtil.loginUser.get(value);
            if(user != null){
                return "redirect:" + target;
            }
        }
        //重定向地址
        session.setAttribute("target", target);
        return "login";
    }


    @GetMapping("/logout")
    public String loginOut(@CookieValue(value = "TOKEN") Cookie cookie, HttpServletResponse response, String target) {
        cookie.setMaxAge(0);
        LoginCacheUtil.loginUser.remove(cookie.getValue());
        response.addCookie(cookie);
        return "redirect:" + target;
    }
}
